//Get JSON from PHP
$(document).ready(function() {
	$.getJSON("DirectoryList.php", function(images){
				var ss = createSlideshowStructure(images);
				slideshow(ss);
			});

});

//Create a 1 dimensional array with URL and caption as attributes from JSON
function createSlideshowStructure(pictures) {
	var slideshowArray = [];
	var i = 0;
	
	$.each(pictures[i], function(key, value) {      
//Throw out first entry, because it is unnecessary 
  	  if (key == "0") {
  		return;
  	  }
  	  
  	  var caption = "";
  	  $.each(value, function(k, url) {
  		 
  		  if (k == "0") {
  			  caption = url;
  			  return;
  		  }
  		  
  		  var image = [];
  		  
  		  image['url'] = url;
  		  image['caption'] = caption;
  		  
  		  slideshowArray[i] = image;
  		  i++;
  	  });
  	  
    });
	
	return slideshowArray;
};

function slideshow(pics) {
	window.setTimeout(showPics, 10000, pics, null);
};

function showPics(photos, nextPic) {
//If the array does not have more than 3 entries, add an array with (new) pictures from the directory to the existing array
	if (!photos[2]) {
		$.getJSON("DirectoryList.php", function(newImages){
			newPhotos = createSlideshowStructure(newImages);
			for (var z = 0; z < newPhotos.length; z++)	{
				photos.push(newPhotos[z]);
			}
//If the following entry is null, take the one after the following
			if (!photos[1])	{
				nextPic = photos[2];
			}
		});
	};
//If no nextPic already exists, create one (important when the function is running for the first time)
	if (!nextPic) {
		nextPic = photos[1];
		currentPic = photos[0];
	} else {
		currentPic = nextPic;
		nextPic = photos[1];
	};
//Change the <img>-tags in HTML
	changeNextPic(nextPic);
	changeCurrentPic(currentPic);
	
	$('.caption').fadeIn('1000');
	$('#pic').fadeIn('1000', function() {
		photos.splice(0, 1);
//Call the same function over and over again
		window.setTimeout(showPics, 10000, photos, nextPic);
	});
};

function changeCurrentPic(currentPicture) {
	$('#pic').fadeOut('1000', function() {
		$('#pic').attr({
			src: currentPicture['url'],
			alt: currentPicture['caption']
		});
	});
	$('.caption').fadeOut('1000', function() {
		$('.caption').html(
				currentPicture['caption']
		);
	});
};

function changeNextPic(nextPicture) {
	$('#nextPic').attr({
		src: nextPicture['url'],
		alt: nextPicture['caption']
	});
};